package com.chenfan.magic.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chenfan.ccp.util.tool.UuidUtil;
import com.chenfan.magic.annation.Log;
import com.chenfan.magic.base.R;
import com.chenfan.magic.constant.MagicConstant;
import com.chenfan.magic.core.IdcEngineEntry;
import com.chenfan.magic.entity.Isv;
import com.chenfan.magic.entity.vo.FieldVo;
import com.chenfan.magic.enums.AppSecureEnum;
import com.chenfan.magic.service.IIsvService;
import com.chenfan.magic.service.impl.FieldHandleComponent;
import com.chenfan.magic.utils.WebKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 魔方控制器
 *
 * @author 周夕
 * @date 2020-02-18 13:40
 */
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/idc-atom-magic")
@Api(value = "魔方服务", tags = "魔方服务接口")
public class MagicController {

    private IdcEngineEntry idcEngineEntry;

    private IIsvService iIsvService;

    private FieldHandleComponent fieldHandleComponent;

    private final String KEY = "_key";
    private final String EXPORT_KEY = "chenfan:download:";

    @Autowired
    @Qualifier("redisTemplate2")
    private RedisTemplate redisTemplate2;

    @Value("${digu.path}")
    private String diguPath;

    @Log
    @RequestMapping(value = "{idOrIndex}", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "执行魔方MQL脚本: 生产线路", notes = "传入魔方 MQL id 或 index(索引)")
    public R prod(HttpServletRequest request, @PathVariable("idOrIndex") String idOrIndex,
                  @RequestParam(value = "isPure", required = false, defaultValue = "0") Integer isPure) {
        Isv isv = iIsvService.getById(request.getHeader("app_key"));
        return idcEngineEntry.execute(idOrIndex, false, isPure.intValue() == 1).encrypt(isv.getAppSecret(), AppSecureEnum.ENCRYPT.getCode());
    }

    @RequestMapping("{idOrIndex1}/{idOrIndex2}")
    @ApiOperation(value = "执行魔方MQL脚本(2): 生产线路", notes = "有序传入两个魔方 MQL id 或 index(索引)")
    public R prod2(HttpServletRequest request, @PathVariable("idOrIndex1") String idOrIndex1, @PathVariable("idOrIndex2") String idOrIndex2) {
        Isv isv = iIsvService.getById(request.getHeader("app_key"));
        R r1 = idcEngineEntry.execute(idOrIndex1);
        R r2 = idcEngineEntry.execute(idOrIndex2);
        r1.getData().putAll(r2.getData());
        return r1.encrypt(isv.getAppSecret(), AppSecureEnum.ENCRYPT.getCode());
    }

    /**
     * 下载接口,返回url到第谷下载
     *
     * @return
     */
    @Log
    @GetMapping("/download/{id}")
    public R download(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) throws IOException {
        String key = UuidUtil.generateUuid();
        redisTemplate2.opsForValue().set(EXPORT_KEY + key, KEY, 1, TimeUnit.DAYS);
        StringBuilder sb = new StringBuilder();
        sb.append(MagicConstant.DIGU_PATH).append(id)
                .append("?_key=")
                .append(key)
                .append("&passport=dc618&templateId=" + id)
                .append("&shopIds=" + request.getParameter("shopIds"))
                .append("&" + request.getQueryString());
        return R.data(sb.toString());
    }

    /**
     * 下载接口,返回url到第谷下载
     *
     * @return
     */
    @Log
    @PostMapping("/download2/{id}")
    public R download2(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) throws IOException {
        String key = UuidUtil.generateUuid();
        redisTemplate2.opsForValue().set(EXPORT_KEY + key, KEY, 1, TimeUnit.DAYS);
        StringBuilder sb = new StringBuilder();
        sb.append(MagicConstant.DIGU_PATH).append(id)
                .append("?_key=")
                .append(key)
                .append("&passport=dc618&templateId=" + id);
        Map<String, Object> result = new HashMap<>(8), params = new HashMap<>(8);
        try {
            params.putAll(WebKit.getParams(request));
        } catch (Exception e) {
            log.error("download2 error:{}", e);
        }
        params.put("shopIds", request.getParameter("shopIds"));
        result.put("url", sb.toString());
        result.put("params", params);
        return R.data(result);
    }

    /**
     * 保存列表勾选字段历史记录
     *
     * @param request
     * @param vo
     * @return
     */
    @PostMapping("/list/saveFieldsRecord")
    public R saveFieldsRecord(HttpServletRequest request, @RequestBody FieldVo vo) {
        Isv isv = iIsvService.getById(request.getHeader("app_key"));
        fieldHandleComponent.saveFields(request, vo);
        return R.success().encrypt(isv.getAppSecret(), AppSecureEnum.ENCRYPT.getCode());
    }


    /**
     * 获取列表勾选字段历史记录
     *
     * @param request
     * @return
     */
    @GetMapping("/list/get")
    public R get(HttpServletRequest request) {
        Isv isv = iIsvService.getById(request.getHeader("app_key"));
        fieldHandleComponent.getList(request);
        return R.success().encrypt(isv.getAppSecret(), AppSecureEnum.ENCRYPT.getCode());
    }

}
